// pages/home-page/add-customer/addCustomer.js
const app = getApp()
import util from '../../../utils/util'
const { validateAll } = require('../../../utils/validator.js')
const infoObj = {
  address: '',
  annualIncome: '',
  birthday: '',
  idNumber: '',
  idType: '0',
  name: '',
  phoneNum: '',
  profession: '',
  sex: '',
}
Page({
  /**
   * 页面的初始数据
   */
  validator (rule, value, callback) {
    console.log(this)
    const reg = /^[0-9a-zA-Z]{4,20}$/
    if (value && !reg.test(value)) {
      callback(new Error('证件号码为4到20位数字和字母'))
    } else {
      callback()
    }
  },
  data: {
    info: {...infoObj},
    members: [],
    idTypeList: [],
    professionList: [],
    annualIncomeList: [],
    customerId: '',
    rules: {
      name: [
        { required: true, message: '姓名必填' },
        { validator(rule, value, callback) {
            const reg = /^[a-zA-Z\u4e00-\u9fa5]{2,10}$/
            if (!reg.test(value)) {
              callback(new Error('姓名需为2-10位中文或英文字符'))
            } else {
              callback()
            }
          } },
      ],
      sex: [
        { required: true, message: '性别必填' },
      ],
      birthday: [
        { required: true, message: '出生日期必填' },
      ],
      idNumber: [
        { validator: (rule, value, callback) => {
          console.log(this)
          const reg = /^[0-9a-zA-Z]{4,20}$/
          if (value && !reg.test(value)) {
            callback(new Error('证件号码为4到20位数字和字母'))
          } else {
            callback()
          }
        } },
      ],
      phoneNum: [
        { validator(rule, value, callback) {
          const reg = /^[0-9]{11}$/
          if (value && !reg.test(value)) {
            callback(new Error('手机号码为11位数字'))
          } else {
            callback()
          }
        } }
      ],
      address: [
        { validator(rule, value, callback) {
          const reg = /^[\u4e00-\u9fa50-9a-zA-Z]{2,200}$/
          if (value && !reg.test(value)) {
            callback(new Error('地址为2-200位中文或英文或数字'))
          } else {
            callback()
          }
        } }
      ],
    },
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getIncomeList()
    this.getIdTypeList()
    this.getProfessionList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  changeInfo: function (e) {
    console.log(e.detail.info)
    this.setData({
      info: e.detail.info
    })
  },
  addFamilyMember () {
    let { members } = this.data
    let info = {...infoObj}
    let relation = ''
    let sex = ''
    if (members.length <= 0) {
      relation = 'couple'
      info.sex && (sex = info.sex === '男' ? '女' : '')
    }
    const i = {
      relation,
      ...info,
      sex
    }
    members.push(i)
    this.setData({
      members
    })
  },
  changeMemberInfo: function (e) {
    const {index} = e.currentTarget.dataset
    this.setData({
      [`members[${index}]`]: e.detail.info
    })
    console.log(this.data.members)
  },
  getIncomeList: function () {
    app.api.post({
      url: 'customer_manage_allAnnualIncome'
    }).then(res => {
      this.setData({
        annualIncomeList: res
      })
    })
  },
  getIdTypeList: function () {
    app.api.post({
      url: 'customer_manage_allIdType'
    }).then(res => {
      this.setData({
        idTypeList: res
      })
    })
  },
  getProfessionList: function () {
    app.api.post({
      url: 'tag_manage_getProfessions'
    }).then(res => {
      this.setData({
        professionList: res
      })
    })
  },
  delMember: function (e) {
    const { index } = e.currentTarget.dataset
    let { members } = this.data
    members.splice(index, 1)
    this.setData({
      members
    })
  },
  submit: function () {
    const { info, members } = this.data
    let flag = true
    validateAll(this.data.rules, info, (valid) => {
      if (!valid) {
        flag = false
      }
    })
    flag && members.some(m => {
      const mRules = {
        ...this.data.rules,
        relation: [
          { required: true, message: '关系必填' },
        ],
      }
      validateAll(this.data.rules, m, (valid) => {
        if (!valid) {
          flag = false
          return true
        }
      })
    })
    if (flag) {
      this.setData({
        loading: true
      })
      app.api.post({
        url: 'customer_manage_add',
        data: {
          customer: info,
          contactList: members
        }
      }).then(res =>{
        wx.redirectTo({
          url: `/pages/home-page/customer-tag/customerTag?customerId=${res.data}&origin=1`
        })
      }).finally(() => {
        this.setData({
          loading: false
        })
      })
    }
  },
  saveTag: function () {
    const { customerId } = this.data
    wx.navigateTo({
      url: `/pages/home-page/customer-analysis/customerAnalysis?id=${customerId}`
    })
  },
})